package com.zh.webflux.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;

/**
 * @author ZH
 * @date 13:01 2023/5/7
 */
@Slf4j
public class MyDataBufferUtil {

    public static Mono<String> dataBufferToString(Flux<DataBuffer> dataBufferFlux){
        Mono<DataBuffer> dataBufferMono = DataBufferUtils.join(dataBufferFlux);

        return dataBufferMono.map(dataBuffer ->
             dataBufferToString(dataBuffer)
        );
    }

    public static String dataBufferToString(DataBuffer dataBuffer){
            try {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                Channels.newChannel(byteArrayOutputStream)
                        .write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
                String content = byteArrayOutputStream.toString(StandardCharsets.UTF_8);
                return content;
            } catch (IOException ignored) {
                return "";
            }
    }

    /**
     * 将对象转为json数据，并包装为ByteBuffer返回
     *
     * @param object
     * @return
     */
    public static ByteBuffer toJsonByteBuffer(Object object) {
        String jsonData = "";
        try {
            jsonData = new ObjectMapper()
                    .writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("object转换json错误 msg: {}", e.getMessage());
            throw new RuntimeException("object转换json错误 " + e.getMessage());
        }
        log.debug("jsonData = " + jsonData);

        return Unpooled.copiedBuffer(jsonData, StandardCharsets.UTF_8).nioBuffer();
    }
}
